package ua.lk.utils;

public class StringUtils {
	
	public static String ifNull(String value, String ifNullValue)
	{
		return value == null ? ifNullValue : value;
	}

	public static String ifNull(String value)
	{
		return ifNull(value,"");
	}
	
	public static String ifEmpty(String value, String ifEmptyValue)
	{
		return value.equals("") ? ifEmptyValue : value;
	}
	
	
	
	public static String encrypt(String text, String key)
	{
		StringBuffer result = new StringBuffer("");
		if( text == null || key == null )
			return result.toString();
		int textlen = text.length();
		int keylen = key.length(); 
		if(textlen > 0 && keylen > 0)
		{
			byte[] buffer = text.getBytes();
			byte[] keybuffer = key.getBytes();
			int keyindex = 0;
			byte b;
			for(int i=0;i<textlen;i++)
			{
				b = (byte) (buffer[i] ^ keybuffer[keyindex]);
				if( ++keyindex >= keylen )
					keyindex = 0;
				result.append(String.format("%02X", b));
			}
			
		}
		return result.toString();
	}

	public static String decrypt(String text, String key)
	{
		String result = "";
		if( text == null || key == null )
			return result;
		int textlen = text.length();
		int keylen = key.length();
		if(textlen > 0 && keylen > 0)
		{
			byte[] buffer = new byte[textlen/2];
			for(int i=0;i<textlen;i+=2)
			//	buffer[i/2] = (byte) ((Character.digit(text.charAt(i), 16) << 4) + Character.digit(text.charAt(i+1), 16));
				buffer[i/2] = (byte) Integer.parseInt(text.substring(i, i+2), 16);
			byte[] keybuffer = key.getBytes();
			int keyindex = 0;
			for(int i=0;i<buffer.length;i++)
			{
				buffer[i] ^= keybuffer[keyindex];
				if( ++keyindex >= keylen )
					keyindex = 0;
			}
			result = new String(buffer); 
		}
		return result; 
	}
	
}
